import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
const Login = () => import('@/components/login/Login.vue')
const Register = () => import('@/components/login/Register.vue')
const My = () => import('@/components/my/My.vue')
const UpdatePwd = () => import('@/components/login/UpdatePwd.vue')
const MyHome = () => import('@/components/my/home/Home.vue')
const Settings = () => import('@/components/my/home/Settings.vue')
const Money = () => import('@/components/my/home/Money.vue')
const MoneyRecord = () => import('@/components/my/home/money/Record.vue')
const MoneyPayLoad = () => import('@/components/my/home/money/PayLoad.vue')

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  { path: '/updatepwd', component: UpdatePwd },
  {
    path: '/my',
    component: My,
    meta: { requireAuth: true },
    redirect: '/home',
    children: [
      {
        path: '/home',
        component: MyHome,
        meta: { requireAuth: true },
        children: [
          {
            path: '/home/setting',
            component: Settings,
            meta: { requireAuth: true }
          },
          {
            path: '/home/money',
            component: Money,
            meta: { requireAuth: true },
            redirect: '/home/moneyRec',
            children: [
              {
                path: '/home/moneyRec',
                component: MoneyRecord,
                meta: { requireAuth: true }
              },
              {
                path: '/home/moneyZfb',
                component: MoneyPayLoad,
                meta: { requireAuth: true }
              },
            ]
          },
        ]
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  routes
})

// 配置路由守卫，严禁用户未登录直接进入到页面
router.beforeEach((to, from, next) => {
  // 要访问的页面需要认证的话
  const uid = store.state.uid
  if (to.meta.requireAuth) {
    if (uid) next()
    else {
      const localuid = window.localStorage.getItem('uid')
      if (localuid) {
        store.dispatch('setToken', window.localStorage.getItem('token'))
        store.dispatch('setUser', localuid)
        next()
      } else {
        next('/login')
      }
    }
  } else if (to.path === '/login' && window.localStorage.getItem('uid')) {
    next('/my')
  }
  next()
})

export default router
